package com.xyc.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                .withUser("xyc").password("123").roles("vip1", "vip2", "vip3");
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                .withUser("a").password("123").roles("vip1");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //不拦截静态资源
        //web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定制请求的授权规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //开启登录自动配置
        http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin");

        //开启自动配置的注销的功能
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能 登录成功后，将cookie发给浏览器保存，以后访问页面会带上此cookie，就可以免登录
        // 如果注销，会清除 cookie
        http.rememberMe().rememberMeParameter("rem");

        //关闭默认的csrf认证
        //http.csrf().disable();
    }
}
